//
//  RegistrationViewModel.swift
//  Link
//
//  Created by melvyn on 2018/10/31.
//

import Foundation
import Alamofire
#if canImport(RxCocoa)
import RxSwift
import RxCocoa
#endif

class RegistrationViewModel {
    
    #if canImport(RxCocoa)
    var signupTap: PublishSubject<Void> = PublishSubject()
    var isEnabled: Driver<Bool> = .never()
    var registration: Driver<Result<Bool>> = .never()
    
    init(_ input:(
        username: Observable<String>,
        passwd: Observable<String>,
        verify: Observable<String>
        )) {
        
        let observable = Observable.combineLatest(input.username, input.passwd, input.verify)
        
        isEnabled = observable
            .map { !$0.0.isEmpty && $0.1 == $0.2 }
            .asDriver(onErrorJustReturn: false)
        
        registration = signupTap.withLatestFrom(observable)
            .map({ User.MultipartForm.init(username: $0.0, password: $0.1) })
            .flatMapLatest({
                APIClient.default.rx.attemptAppRegistration($0)
            })
            .asDriver(onErrorJustReturn: .failure(APIError.undefine))
    }
    #else
    var input: (String, String) = ("", "") {
        didSet {
            isEnabled(!input.0.isEmpty && !input.1.isEmpty)
        }
    }
    var registration: ((Result<Bool>) -> Void)?
    var isEnabled: ((Bool) -> Void)?
    
    init() {}
    
    @objc func signupEventHandler() {
        let multipartForm = User.MultipartForm.init(username: input.0, password: input.1)
        
        let completion = registration ?? { _ in }
        APIClient.default.attemptAppRegistration(multipartForm, completionHandler: completion)
    }
    #endif
}
